//
//  ClickCommentCtl.m
//  diaoyuren
//
//  Created by 钓鱼人 on 16/3/5.
//  Copyright © 2016年 game. All rights reserved.
//

#import "ClickCommentCtl.h"
#import "SelectNavView.h"
#import "TZImagePickerController.h"
#import "TZImageManager.h"
#import "TZAssetModel.h"
#import "UIView+Layout.h"
#import "ClickComentView.h"
#import "AFHTTPRequestOperationManager.h"
#import "AFURLSessionManager.h"
#import "PersonEditModel.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#define XXXDDD 10
#define WWWWW  (SCREEN_WIDTH-XXXDDD*5)/4
@interface ClickCommentCtl ()<TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,strong) NSMutableArray *imagess;
@property (nonatomic,strong) SelectNavView *naV;
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) ClickComentView *commentView;
@property (nonatomic,strong) NSMutableArray *imageDataary;
@property (nonatomic,assign) NSInteger imageLoadCount;
@property (nonatomic,strong) NSMutableDictionary *dic;
@property (nonatomic,strong) NSString *loadImageId;
@property (nonatomic,strong) NSMutableArray *filedImgAry;
@end

@implementation ClickCommentCtl

-(NSMutableArray *)filedImgAry{
    
    if (!_filedImgAry) {
        _filedImgAry = [NSMutableArray array];
    }
    return _filedImgAry;
}

-(NSMutableDictionary *)dic{
    if (!_dic) {
        _dic = [NSMutableDictionary dictionary];
    }
    return _dic;
}

-(NSMutableArray *)imageDataary{
    if (!_imageDataary) {
        _imageDataary = [NSMutableArray array];
    }
    return _imageDataary;
}

-(ClickComentView *)commentView{
    if (!_commentView) {
        _commentView = [[NSBundle mainBundle]loadNibNamed:@"ClickComentView" owner:nil options:nil].lastObject;
        _commentView.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT/3);
    }
    return _commentView;
}
-(UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, Height(_commentView), SCREEN_WIDTH, SCREEN_HEIGHT-Height(_commentView))];
        
        _scrollView.backgroundColor = RGBA(230, 230, 238, 0.8);
        [self.view addSubview:self.scrollView];
    }
    return _scrollView;
}

-(NSMutableArray *)imagess{
    if (!_imagess) {
        _imagess  = [NSMutableArray array];
    }
    return _imagess;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.app.myTabBar.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self CreatNavView];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
}

-(void)CreatNavView{
    self.naV = [[SelectNavView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    self.naV.titile.text = @"传照片";
    self.naV.share.titleLabel.font = font(SCREEN_WIDTH*0.05);
    [self.naV.share setTitle:@"提交" forState:UIControlStateNormal];
    self.naV.share.y = 21;
    self.naV.share.x = SCREEN_WIDTH - 60;
    [self.view addSubview:self.naV];
    [self.naV.bacBtn addTarget:self action:@selector(Back) forControlEvents:UIControlEventTouchUpInside];
    [self.naV.share addTarget:self action:@selector(Tijiao) forControlEvents:UIControlEventTouchUpInside];
}


-(void)Back{
    
    
    if (self.imagess.count==0&&self.commentView.textView.text.length==0) {
        
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        
        UIAlertController *aler = [UIAlertController alertControllerWithTitle:nil message:@"是否保存草稿?" preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *ToPhone = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       
            [self Edit];
        }];
        
        UIAlertAction *ToImage = [UIAlertAction actionWithTitle:@"不保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self.navigationController popViewControllerAnimated:YES];
            
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        
        [aler addAction:ToPhone];
        [aler addAction:ToImage];
        [aler addAction:cancel];
        [self presentViewController:aler animated:YES completion:nil];
        
    }
}
#pragma mark---保存草稿箱
-(void)Edit{
    if (self.commentView.scroceString.length==0) {
        self.commentView.scroceString = @"0";
    }
    
    NSString *name = @"钓场点评[点评]";
    if (self.isyujudian) {
        name = @"渔具店点评[照片]";
        
    }

    NSDictionary *dic = @{
                          @"time":[Manager AchiveNowTime],
                          @"images":self.imageDataary,
                          @"name":name,
                          @"type":@"DcComment",
                          @"text":self.commentView.textView.text,
                          @"Id":self.Id,
                          @"scroce":self.commentView.scroceString,
                          @"isyujud":[NSString stringWithFormat:@"%d",self.isyujudian],
                          };
    
    self.filedImgAry = [NSMutableArray arrayWithContentsOfFile:[Manager editeFilePath]];
    
    [self.filedImgAry insertObject:dic atIndex:0];
    
    [self.filedImgAry writeToFile:[Manager editeFilePath] atomically:YES];
    
    [self.imageDataary removeAllObjects];
    if ([self.deleget respondsToSelector:@selector(GetToEdit)]) {
        [self.deleget GetToEdit];
    }
    
    [self.navigationController popViewControllerAnimated:YES];

}
#pragma mark---点击草稿箱中修改调用此方法
-(void)setEditDic:(NSDictionary *)editDic{
    _editDic = editDic;
    
    PersonEditModel *model = [[PersonEditModel alloc]initWithDictionary:_editDic error:nil];
    self.commentView.sroce.text = [NSString stringWithFormat:@"%@分",model.scroce];
    [self.commentView.starRating StarForegroundViewWithScore:model.scroce];
    self.commentView.scroceString = model.scroce;
    
    self.commentView.textView.text = model.text;
    [self.commentView textViewDidChange:self.commentView.textView];
    
    [self.imageDataary addObjectsFromArray:_editDic[@"images"]];
    
    for (NSData *imagedta in _editDic[@"images"]) {
        
        UIImage *image = [UIImage imageWithData:imagedta];
        
        [self.imagess addObject:image];
    }
    
    [self CretUi];

}

-(void)setIsAnew:(BOOL)isAnew{

    _isAnew = isAnew;
    
    [self Tijiao];
}

-(void)Tijiao{
    
    if (self.commentView.textView.text.length==0) {
        [Manager GetHudWhithText:@"请输入点评内容" AndFatherView:self.view];
    } else if ([self.commentView.sroce.text isEqualToString:@"0分"]){
    
        [Manager GetHudWhithText:@"请打分" AndFatherView:self.view];
    
    } else{
    
    [self.navigationController popViewControllerAnimated:YES];
    self.imageLoadCount = 0;
    self.loadImageId = @"";
    
    if (self.imageDataary.count==0) {
        [[Manager sharedManager]RequestWhithURL:GetFormhash AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
            
            if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {

                [self GetAddComentWhithFormhash:responseObject[@"data"][@"formhash"]];
            }
        }];
        
    }else{
    
        if (self.imageDataary.count!=0) {
            [[Manager sharedManager]RequestWhithURL:GetFormhash AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
                
                if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
                    
                    
                    for (int i=0; i<self.imageDataary.count; i++) {
                        
                        [self PostImageWhithFormhash:responseObject[@"data"][@"formhash"] WhithImageData:self.imageDataary[i] AndName:[NSString stringWithFormat:@"%d.jpg",i+1]];
                    }
                    
                }
            }];
            
        }
    }
}
}

#pragma mark--上传文字与分数
-(void)GetAddComentWhithFormhash:(NSString *)formhash{
    NSString *iddd = @"d_id";
    if (self.isyujudian) {
        iddd = @"y_id";
    }
//    NSLog(@"%@",self.Id);
    NSDictionary *dic = @{
                          @"formhash":formhash,
                          iddd:self.Id,
                          @"comment":self.commentView.textView.text,
                          @"score":self.commentView.scroceString,
                          @"pic_ids":self.loadImageId,
                          };
    
//    NSLog(@"%@",self.url);
    [[Manager sharedManager]ResponseWhithURL:self.url AndParameter:dic AndCompletionType:^(id responseObject, DIEError *error) {
        
//        NSLog(@"文字%@",responseObject);
//        NSLog(@"文字%@",responseObject[@"message"]);
        if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
            if ([self.deleget respondsToSelector:@selector(Finish)]) {
                [self.deleget Finish];
            }
            
        }
        
    }];
    
}

#pragma mark--上传图片
-(void)PostImageWhithFormhash:(NSString *)formhash WhithImageData:(NSData *)imageData AndName:(NSString *)name{
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    NSString *url = islanUploadImage;
    if (self.isyujudian) {
        url = dianpuUploadImage;
    }
    
    AFHTTPRequestOperation *operation = [manager POST:url  parameters:@{@"formhash":formhash,@"id":self.Id,@"type":@"2"} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        [formData appendPartWithFileData:imageData name:@"Filedata" fileName:name mimeType:@"application/octet-stream"];
        
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
            
            self.imageLoadCount +=1;
            
            NSString *sss = [NSString stringWithFormat:@",%@",responseObject[@"data"][@"dp_id"]];
            self.loadImageId = [ self.loadImageId stringByAppendingString:sss];
            
            if (self.imageLoadCount==self.imageDataary.count) {//图片上传完毕,就上传文字
             
                [self GetAddComentWhithFormhash:formhash];
            }


        }else{
            
            [self Edit];
            if ([self.deleget respondsToSelector:@selector(CommentupLoadfailure)]) {
                
                [self.deleget CommentupLoadfailure]; // 通知执行协议方法
  }
            
        }
 
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [self Edit];
        if ([self.deleget respondsToSelector:@selector(CommentupLoadfailure)]) {
            
            [self.deleget CommentupLoadfailure]; // 通知执行协议方法
        }
        
    }];
    
    
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        
        float p = (float)totalBytesWritten / totalBytesExpectedToWrite;
        
        [self.dic setValue:[NSString stringWithFormat:@"%f",p] forKey:name];
        
        __block CGFloat  ffff ;
        [self.dic enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            
            ffff += [obj floatValue];
            
        }];
        
        if ([self.deleget respondsToSelector:@selector(CommentupLoadeImageProgress:)]) {
            
            [self.deleget CommentupLoadeImageProgress:(ffff/self.imageDataary.count)]; // 通知执行协议方法
        }
        
    }];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.commentView];
    [self CretUi];
}
// 用户选择好了图片，如果assets非空，则用户选择了原图。
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets{
    
    [self.imagess addObjectsFromArray:photos];
    
    [self CretUi];
    
    for (UIImage *portraitImg in photos) {
        
        if (portraitImg != nil) { //当图片不为空时显示图片并保存图片
            
            UIImage *image = [Manager imageCompressForWidth:portraitImg targetWidth:800];
            
            //            [UIImageJPEGRepresentation(image,0.8) writeToFile:@"/Users/Shanancheng/Desktop/shangchuan.jpg" atomically:YES];
            
            [self.imageDataary addObject:UIImageJPEGRepresentation(image,0.8)];
        }
    }

}


-(void)CretUi{
    
    [self.scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    NSInteger count = self.imagess.count;
    
    if (count<9) {
        count = self.imagess.count+1;
    }
    
    for (int i= 0; i<count; i++) {
        
        CGFloat row = i%4;
        CGFloat lod = i/4;
        
        CGFloat xx = XXXDDD+(XXXDDD+WWWWW)*row;
        CGFloat yy = XXXDDD +(XXXDDD+WWWWW)*lod;
        
        UIButton *imageView = [UIButton buttonWithType:UIButtonTypeCustom];
        
        imageView.frame = CGRectMake(xx, yy, WWWWW, WWWWW);
        
        imageView.backgroundColor = linColor;
        
        imageView.tag = i+10000;
        
         imageView.imageView.contentMode  = UIViewContentModeScaleAspectFill;
        
        if (i<self.imagess.count) {
            
            imageView.imageView.contentMode = UIViewContentModeScaleAspectFill;
            [imageView setImage:_imagess[i] forState:UIControlStateNormal];
            UIButton *shanchu = [UIButton buttonWithType:UIButtonTypeCustom];
            
            shanchu.frame = CGRectMake(WWWWW-25, 0, 25, 25);
            shanchu.tag  = imageView.tag + 100;
            
             [shanchu setImage:[UIImage imageNamed:@"delete_pic"] forState:UIControlStateNormal];
            [imageView addSubview:shanchu];
            
            [shanchu addTarget:self action:@selector(shanchu:) forControlEvents:UIControlEventTouchUpInside];
            
        }else{
            
            imageView.backgroundColor = [UIColor whiteColor];
             [imageView setBackgroundImage:[UIImage imageNamed:@"add_pic"] forState:UIControlStateNormal];
            
            [imageView addTarget:self action:@selector(AddImage) forControlEvents:UIControlEventTouchUpInside];
        }
        
        [self.scrollView addSubview:imageView];
        
        self.scrollView.contentSize = CGSizeMake(0, Height(imageView)+10);
    }
    
}

-(void)shanchu:(UIButton *)btn{
    
    NSInteger count = self.imagess.count;
    [self.imagess removeObjectAtIndex:btn.tag-100-10000];
    
    UIButton *bbb = [self.view viewWithTag:btn.tag-100];
    
    [bbb removeFromSuperview];
    
    for (int i=(int)btn.tag-100-10000+1; i<count+1; i++) {
        
        UIButton *tttt = [self.view viewWithTag:i+10000];
        
        tttt.tag -= 1;
        
        UIButton *shan = [self.view viewWithTag:i+10000+100];
        shan.tag -=1;
        
        if (tttt.x!=10) {
            
            [UIView animateWithDuration:0.3 animations:^{
                tttt.x -= tttt.width+10;
            }];
            
        }else{
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [UIView animateWithDuration:0.18 animations:^{
                    tttt.x = SCREEN_WIDTH-tttt.width-10;
                    tttt.y -= tttt.height+10;
                }];
            });
        }
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        /**
         *  当相册列表有9张（没有添加btn） 到删除一张 到8张得时候 将添加btn添加上去
         */
        if (self.imagess.count==8) {
            
            UIButton *imageView = [UIButton buttonWithType:UIButtonTypeCustom];
            imageView.tag = 8+10000;
            
            CGFloat row = 8%4;
            CGFloat lod = 8/4;
            
            CGFloat xx = XXXDDD+(XXXDDD+WWWWW)*row;
            CGFloat yy = XXXDDD +(XXXDDD+WWWWW)*lod;
            
            imageView.frame = CGRectMake(xx, yy, WWWWW, WWWWW);

            [imageView setBackgroundImage:[UIImage imageNamed:@"add_pic"] forState:UIControlStateNormal];
            imageView.backgroundColor = [UIColor whiteColor];
            [imageView addTarget:self action:@selector(AddImage) forControlEvents:UIControlEventTouchUpInside];
            
            [self.scrollView addSubview:imageView];
        }
        
    });
}

-(void)AddImage{
    UIAlertController *aler = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *ToPhone = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }];
    
    UIAlertAction *ToImage = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self LocalPhoto];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [aler addAction:ToPhone];
    [aler addAction:ToImage];
    [aler addAction:cancel];
    [self presentViewController:aler animated:YES completion:nil];
    
}
/**
 *  打开相册
 */
-(void)LocalPhoto{
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
    imagePickerVc.SelectImagesCount = self.imagess.count;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingVideo = NO;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark---调用相机
-(void)takePhoto{
    BOOL isCameraValid = YES;
    if(iOS7)
    {
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus != AVAuthorizationStatusAuthorized)
        {
            isCameraValid = NO;
            NSString *appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleDisplayName"];
            if (!appName) appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleName"];
            [self ShowAlertWhthTitle:@"提示" Message:[NSString stringWithFormat:@"请在%@的\"设置-隐私-相机\"选项中，\r允许%@访问你的手机相机。",[UIDevice currentDevice].model,appName] CancelButtonTitle:@"好"];
        }else{
            
            UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
            
            if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
                
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.delegate = self;
                picker.sourceType = sourceType; //资源类型为照相机
                [self presentViewController:picker animated:YES completion:nil];
                
            }
        }
    }
}

#pragma mark---相册相机回调协议方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    //    [UIImagePNGRepresentation(portraitImg) writeToFile:@"/Users/diaoyuren/Desktop/压缩前.png" atomically:YES];
    UIImage *image = [Manager   imageByScalingToMaxSize:portraitImg WhithMAXWIdth:150];//压缩处理
    
    if (portraitImg != nil) { //当图片不为空时显示图片并保存图片
        [self.imagess addObject:image];
        [self CretUi];
        
        UIImage *image = [Manager imageCompressForWidth:portraitImg targetWidth:800];
        
        //            [UIImageJPEGRepresentation(image,0.8) writeToFile:@"/Users/Shanancheng/Desktop/shangchuan.jpg" atomically:YES];
        
        [self.imageDataary addObject:UIImageJPEGRepresentation(image,0.8)];
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];//关闭相册界面
}

@end